const log4js = require('koa-log4');
const logger = log4js.getLogger('routes::adsense');
const router = require('koa-router')();
exports = module.exports = router;
const mongodb = require('mongodb');
const ObjectId = mongodb.ObjectId;

const adsense_service = require(global.prefixPath + '/services/adsense');

router.get('/adsenses', async (ctx, next) => {
	ctx.checkQuery('q').notEmpty("query param is missing!").isJSON("param must be a json string!");

	if (ctx.errors) {
		ctx.status = 400;
		ctx.body = ctx.errors;
		return;
	}

	let q = JSON.parse(ctx.query.q);

	try {
		let result = await adsense_service.find(q);
		ctx.body = result;
	} catch (err) {
		throw err;
	}

});

/**
 * 
 */
router.get('/adsense/:id', async (ctx, next) => {
	try {
		let adsense_id = ctx.params.id;
		let result = await adsense_service.findById(adsense_id);
		ctx.body = result;
	} catch (err) {
		throw err;
	}
});

/**
 * 添加广告信息
 */
router.post('/adsense', async (ctx, next) => {
	try {
		let adsense = ctx.request.body;
		let result = await adsense_service.insert(adsense);
		ctx.body = result;
	} catch (err) {
		throw err;
	}
});

/**
 * 修改广告信息
 */
router.put('/adsense/:id', async (ctx, next) => {
	try {
		let adsense_id = ctx.params.id;
		let adsense = ctx.request.body;
		adsense._id = new ObjectId(adsense_id);
		let result = await adsense_service.save(adsense);
		ctx.body = result;
	} catch (err) {
		throw err;
	}
});

/**
 * 删除广告信息
 */
router.delete('/adsense/:id', async (ctx, next) => {
	try {
		let adsense_id = ctx.params.id;
		let result = await adsense_service.delById(adsense_id);
		ctx.body = result;
	} catch (err) {
		throw err;
	}
});